package com.example.demo.security.sysUser.controller;

import com.example.demo.security.sysGroup.service.GroupService;
import com.example.demo.security.sysUser.entity.UserBean;
import com.example.demo.security.sysUser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private GroupService groupService;

    private final String file_path="security/sysUser/";

    /**
     * 跳转主页（框架）
     * @author 自嘲
     * @return
     */
    @RequestMapping("toMenu")
    public String toMenu(){
        String url="security/index";
        return url;
    }

    /**
     * 跳转聊天信息页
     * @author 自嘲
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("toIndex")
    public String toIndex(HttpServletRequest request,String id){
        Map<String,String> map=new HashMap<String,String>();
        String[] str=id.split(",");
        String state=str[0];
        String ids=str[1];
        String name;
        if (state.equals("1")){
            name=userService.queryUserNameById(Integer.parseInt(ids));
        }else {
            name=groupService.queryGroupNameById(Integer.parseInt(ids));
        }
        map.put("name",name);
        map.put("state",state);
        map.put("id",ids);
        map.put("userId",request.getSession().getAttribute("id").toString());
        request.setAttribute("map",map);
        return file_path+"index";
    }
    @RequestMapping("toTool")
    public String toTool(){
        return "security/tool";
    }

    @RequestMapping("toDelFriend")
    @ResponseBody
    public String toDelFriend(HttpServletRequest request,Integer friendId){
        Integer id=Integer.parseInt(request.getSession().getAttribute("id").toString());
        try {
            Integer i=userService.exitFriend(id,friendId);
            if (i==0){
                return "删除好友失败！";
            }else {
                return "删除好友成功！";
            }
        }catch (Exception e){
            return "系统异常！";
        }
    }
    /**
     * 加载用户好友
     * @author 自嘲
     * @param request
     * @return
     */
    @RequestMapping("list")
    @ResponseBody
    public List<UserBean> list(HttpServletRequest request){
        List<UserBean> list=null;
        try {
            String id=request.getSession().getAttribute("id").toString();
            list=userService.queryFriends(Integer.parseInt(id));
        }catch (Exception e){
            list=null;
        }
        return list;
    }

}
